<?php

namespace app\admin\model;

use think\Model;
/**
 * 规格模型类
 */
class Specifications extends Model
{
    public function DeleteById($id) {
        if ($this->where('id', $id)->count() == 1) {
            $this->where('id', $id)->delete();

            return Result(1, '删除成功');
        }

        return Result(0, '提供的数据id不正确');
    }

    public function Created($name)
    {
        if ($this->where('name', $name)->count() > 0) {
            return Result(0, '该规格已存在');
        }

        $id = $this->insertGetId(['name' => $name]);

        return Result(1, '添加成功', [
            'id' => $id
        ]);
    }

    public function GetInfo($id)
    {
        if ($this->where('id', $id)->count() == 0) {
            return Result(0, '该规格不存在');
        }

        $specifications = $this->where('id', $id)->find()->toArray();

        return Result(1, '', [
            'specifications' => $specifications
        ]);
    }

    public function GetList($page, $option)
    {
        $buildDb = function () use ($option) {
            $db = $this->where('state', 1);

            if(array_key_exists('name', $option) &&!empty($option['name'])) {
                $db = $db->where('name', $option['name']);
            }

            return $db;
        };
        $count = $buildDb()->count();
        $list = $buildDb()->page($page, 50)->select();

        return Result(1, '', [
            'count' => $count,
            'pageSize' => 50,
            'list' => $list
        ]);

    }

    public function ModifyData($id, $option) 
    {
        if ($this->where('id', $id)->count() == 1) {
            $this->where('id', $id)->data($option)->update();

            return Result(1, '修改成功');
        }

        return Result(0, '提供的数据id不正确');
    }
}
